package com.mars.diancan.service.impl;

import com.mars.diancan.common.OrderStatusEnum;
import com.mars.diancan.common.PayStatusEnum;
import com.mars.diancan.common.ResultEnum;
import com.mars.diancan.converter.OrderMaster2OrderDTOConverter;
import com.mars.diancan.dao.OrderDetailRepository;
import com.mars.diancan.dao.OrderMasterRepository;
import com.mars.diancan.dto.CartDTO;
import com.mars.diancan.dto.OrderDTO;
import com.mars.diancan.exception.DiancanException;
import com.mars.diancan.pojo.OrderDetail;
import com.mars.diancan.pojo.OrderMaster;
import com.mars.diancan.pojo.ProductInfo;
import com.mars.diancan.service.OrderService;
import com.mars.diancan.service.PayService;
import com.mars.diancan.service.ProductInfoService;
import com.mars.diancan.service.PushMessageService;
import com.mars.diancan.utils.KeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单services
 * @author MARS
 * @date 2018/6/25
 */
@Service
@Transactional
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private ProductInfoService productInfoService;

    @Autowired
    private OrderMasterRepository orderMasterRepository;

    @Autowired
    private OrderDetailRepository orderDetailRepository;

    @Autowired
    private PayService payService;

    @Autowired
    private PushMessageService pushMessageService;

  @Override
    public OrderDTO create(OrderDTO orderDTO) {
        String orderId = KeyUtil.genUniqueKey();
        // 提前初始化总价
        BigDecimal orderAmount = new BigDecimal(BigInteger.ZERO);

        // 购物车初始化
//        List<CartDTO> cartDTOList = new ArrayList<>();

        // 1.查询商品
        for (OrderDetail orderDetail :orderDTO.getOrderDetailList()){
            // 获取购物车中商品详情信息
            ProductInfo productInfo = productInfoService.findOne(orderDetail.getProductId());
            // 如果购物车中商品 ，在商品表（product_info）中都不存在，则抛出异常
            if (productInfo == null) {
                throw new DiancanException(ResultEnum.PRODUCT_NOT_EXIST);
            }
            // 商品不为null，获取购物车中商品的总价
            // 计算订单总价 Bigdecimal的乘法
            orderAmount = productInfo.getProductPrice()
                    .multiply(new BigDecimal(orderDetail.getProductQuantity()))
                    .add( orderAmount);
            // 订单详情入库
            // 每获取一个商品详情数据，就存入订单详情表中（order_detail中）
            BeanUtils.copyProperties(productInfo,orderDetail);
            orderDetail.setDetailId(KeyUtil.genUniqueKey());
            // 订单id在创建的时候就应该产生了
            orderDetail.setOrderId(orderId);
            orderDetail.setCreateTime(new Date());
            orderDetail.setUpdateTime(new Date());
            orderDetailRepository.save(orderDetail);

            // 用lamdb表达式
//            CartDTO cartDTO = new CartDTO(orderDetail.getProductId(),orderDetail.getProductQuantity());
//            cartDTOList.add(cartDTO);
        }

        // 3.写入订单主表数据库
        OrderMaster orderMaster = new OrderMaster();
        // 注意BeanUtils在copy时的顺序
        orderDTO.setOrderId(orderId);
        BeanUtils.copyProperties(orderDTO,orderMaster);
        orderMaster.setOrderAmount(orderAmount);
        orderMaster.setOrderStatus(OrderStatusEnum.NEW.getCode());
        orderMaster.setPayStatus(PayStatusEnum.WAIT.getCode());
        orderMaster.setCreateTime(new Date());
        orderMaster.setUpdateTime(new Date());
        orderMasterRepository.save(orderMaster);

        // 4.扣库存(利用lamdb表达式),统一扣库存
        List<CartDTO> cartDTOList = new ArrayList<>();
        cartDTOList = orderDTO.getOrderDetailList()
                .stream()
                .map(e -> new CartDTO(e.getProductId(),e.getProductQuantity()))
                .collect(Collectors.toList());
        productInfoService.decreaseStock(cartDTOList);

        return orderDTO;
    }

    @Override
    public OrderDTO findOne(String orderId) {
        OrderMaster orderMaster = orderMasterRepository.findOne(orderId);
        if (orderMaster == null) {
            throw new DiancanException(ResultEnum.ORDER_NOT_EXIST);
        }

        // 获取订单详情
        List<OrderDetail> orderDetailList = orderDetailRepository.findByOrderId(orderId);
        if (CollectionUtils.isEmpty(orderDetailList)) {
            throw new DiancanException(ResultEnum.ORDERDETAIL_NOT_EXIST);
        }

        // 组装OrderDTO
        OrderDTO orderDTO = new OrderDTO();
        BeanUtils.copyProperties(orderMaster,orderDTO);
        orderDTO.setOrderDetailList(orderDetailList);
        return orderDTO;
    }

    @Override
    public Page<OrderDTO> findList(String buyerOpenid, Pageable pageable) {
        // 获取订单主表列表
        Page<OrderMaster> orderMasterPage = orderMasterRepository.findByBuyerOpenid(buyerOpenid,pageable);
        //  将OrderMaster --> 转化为OrderDTO
        List<OrderDTO> orderDTOList = OrderMaster2OrderDTOConverter.converter(orderMasterPage.getContent());
        // PageImpl的参数：List<T> content, Pageable pageable, long total
        Page<OrderDTO> orderDTOPage = new PageImpl<OrderDTO>(orderDTOList,pageable,orderMasterPage.getTotalElements());
        return orderDTOPage;
    }

    /**
     * 取消订单
     * 1.首先应该判断当前订单状态
     * @param orderDTO
     * @return
     */
    @Override
    @Transactional
    public OrderDTO cancel(OrderDTO orderDTO) {
       // 转换
        OrderMaster orderMaster = new OrderMaster();

       // 判断订单当前状态
        if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
            log.error("取消订单，订单状态不正确,orderId={},orderStatus={}",orderDTO.getOrderId(),orderDTO.getOrderStatus());
            throw new DiancanException(ResultEnum.ORDER_STATUS_ERROR);
        }
       // 修改订单状态
        orderDTO.setOrderStatus(OrderStatusEnum.CANCEL.getCode());
        BeanUtils.copyProperties(orderDTO,orderMaster);
        OrderMaster updateOrderMaster = orderMasterRepository.save(orderMaster);

        if (updateOrderMaster == null){
            log.error("取消订单，更新失败,orderMaster={}",orderMaster);
            throw new DiancanException(ResultEnum.ORDER_UPDATE_FAIL);
        }
        // 返还库存,判断订单中有没有商品，没有商品就不返还库存了
        if (CollectionUtils.isEmpty(orderDTO.getOrderDetailList())) {
            log.error("取消订单，订单中无商品详情,orderDTO={}",orderDTO);
            throw new DiancanException(ResultEnum.ORDER_DETAIL_EMPTY);
        }
        List<CartDTO> cartDTOList = orderDTO.getOrderDetailList()
                .stream()
                .map(e -> new CartDTO(e.getProductId(),e.getProductQuantity()))
                .collect(Collectors.toList());

        productInfoService.increaseStock(cartDTOList);
       // 如果已支付，需要给用户退款
        if (orderDTO.getPayStatus().equals(PayStatusEnum.SUCCESS.getCode())) {
            // 取消订单
            payService.refund(orderDTO);

        }
        return orderDTO;
    }

    /**
     * 完结订单:
     * 1、判断订单状态
     * 2、修改订单状态（新下单状态可以被修改）
     * @param orderDTO
     * @return
     */
    @Override
    @Transactional
    public OrderDTO finish(OrderDTO orderDTO) {
        // 判断订单状态
        if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
            log.error("完结订单，订单状态不正确,orderId={},orderStatus={}",orderDTO.getOrderId(),orderDTO.getOrderStatus());
            throw new DiancanException(ResultEnum.ORDER_STATUS_ERROR);
        }
        // 修改状态
        orderDTO.setOrderStatus(OrderStatusEnum.FINISHED.getCode());
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderDTO,orderMaster);
        OrderMaster updateResult = orderMasterRepository.save(orderMaster);
        if (updateResult == null) {
            log.error("完结订单，更新失败,orderMaster={}",orderMaster);
            throw new DiancanException(ResultEnum.ORDER_UPDATE_FAIL);
        }

        // 推送微信模板消息,对于消息推送，不建议异常抛出，抛出后，会被此处的事务捕获进行回滚，导致完结订单操作失败
        pushMessageService.orderStatus(orderDTO);

        return orderDTO;
    }

    /**
     * 支付状态 变更
     * @param orderDTO
     * @return
     */
    @Override
    @Transactional
    public OrderDTO paid(OrderDTO orderDTO) {
        // 判断订单状态
        if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
            log.error("订单支付完成，订单状态不正确,orderId={},orderStatus={}",orderDTO.getOrderId(),orderDTO.getOrderStatus());
            throw new DiancanException(ResultEnum.ORDER_STATUS_ERROR);
        }

        // 判断支付状态
        if (!orderDTO.getPayStatus().equals(PayStatusEnum.WAIT.getCode())) {
            log.error("订单支付完成，订单支付状态不正确,orderDTO={}",orderDTO);
            throw new DiancanException(ResultEnum.ORDER_PAY_STATUS_ERROR);
        }
        // 修改支付状态
        orderDTO.setPayStatus(PayStatusEnum.SUCCESS.getCode());
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderDTO,orderMaster);
        OrderMaster updateResult = orderMasterRepository.save(orderMaster);
        if (updateResult == null) {
            log.error("订单支付完成，更新失败,orderMaster={}",orderMaster);
            throw new DiancanException(ResultEnum.ORDER_UPDATE_FAIL);
        }
        return orderDTO;
    }

    /**
     * 查询所有的订单:
     * 1.PageImpl的用法
     * 2.OrderMaster --> OrderDto转换的方法
     * @param pageable
     * @return
     */
    @Override
    public Page<OrderDTO> findList(Pageable pageable) {

        Page<OrderMaster> orderMasterPage = orderMasterRepository.findAll(pageable);

        List<OrderDTO> orderDTOList = OrderMaster2OrderDTOConverter.converter(orderMasterPage.getContent());

        return new PageImpl<OrderDTO>(orderDTOList,pageable,orderMasterPage.getTotalElements());
    }
}
